<template>
    <div class="content">
        <el-card shadow="never">
            <el-row type="flex" justify="space-between">
                <el-form :model="searchForm" size="small" inline style="margin-left: 20px;">
                    <el-form-item label="用户名称">
                        <el-input v-model.trim="searchName" placeholder="请输入用户名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-select v-model="searchSex"  placeholder="请选择用户性别" clearable>
                            <el-option label="男" value="1"></el-option>
                            <el-option label="女" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="search()" size="small">查询</el-button>
                        <el-button size="small" icon="el-icon-refresh-right" @click="handleClear()">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row class="rowSpace" style="margin-left: 20px;">
                <el-col>
                    <div>
                        <el-button type="primary" plain size="small" icon="el-icon-plus" @click="add">新增</el-button>
                        <el-button plain size="small" icon="el-icon-refresh" @click="refresh">刷新</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-dialog  title="新增用户" :visible.sync="dialogAddVisible" width="50%">
              <el-form :model="addForm" ref="addForm" :rules="rules" inline>
                <el-form-item label="用户编号:" prop="id">
                  <el-input  v-model="addForm.id" size="small" placeholder="请输入用户编号" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户名称:" prop="name">
                  <el-input  v-model="addForm.name" size="small" placeholder="请输入用户名称" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户性别:" prop="sex">
                  <el-select v-model="addForm.sex"  placeholder="请选择用户性别" clearable size="small" style="width: 250px;">
                      <el-option label="男" value="1"></el-option>
                      <el-option label="女" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户年龄:" prop="age">
                  <el-input  v-model="addForm.age" size="small" placeholder="请输入用户年龄" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户昵称:" prop="nickname">
                  <el-input  v-model="addForm.nickname" size="small" placeholder="请输入用户电话" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户电话:" prop="mobile">
                  <el-input  v-model="addForm.mobile" size="small" placeholder="请输入用户名称" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户状态:" prop="stateName">
                  <el-input  v-model="addForm.stateName" size="small" placeholder="请输入用户状态" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="已购课程:" prop="courseOrder">
                  <el-input  v-model="addForm.courseOrder" size="small" placeholder="请输入已购课程" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="在学课程:" prop="courseNum">
                  <el-input  v-model="addForm.courseNum" size="small" placeholder="请输入在学课程" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户地址:" prop="address">
                  <el-input  v-model="addForm.address" size="small" placeholder="请输入用户地址" style="width: 250px;" clearable></el-input>
                </el-form-item>
                <div style="text-align: center;">
                  <el-form-item>
                    <el-button size="small" type="primary" @click="onSubmit" style="width: 60px;">保存</el-button>
                    <el-button size="small" @click="dialogAddVisible = false" style="width: 60px;">取消</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </el-dialog>
            <el-divider></el-divider>
            <el-table :data="pageData">
                <el-table-column type="index" label="序号" width="66px" align="center"></el-table-column>
                <el-table-column label="姓名" prop="name" show-overflow-tooltip align="center"></el-table-column>
                <el-table-column label="性别" prop="sex" show-overflow-tooltip align="center">
                    <template slot-scope="scope">
                        <div>
                            {{ scope.row.sex == 1 ? '男' : '女' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="昵称" prop="nickname" show-overflow-tooltip align="center"></el-table-column>
                <el-table-column label="号码" prop="mobile" show-overflow-tooltip align="center"></el-table-column>
                <el-table-column label="状态" prop="stateName" show-overflow-tooltip align="center"></el-table-column>
                <el-table-column label="操作" with="250px" align="center">
                    <template slot-scope="scope">
                        <el-button type="success" plain
                                   size="small"
                                   @click="changeView('/user/detail', scope.row)">
                                   详情</el-button>
                        <el-button type="danger" plain
                                   size="small"
                                   @click="deleteUser(scope.row.id)">
                                   删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row style="margin-top: 20px;">
                <el-col style="text-align: center">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 50, 100]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script>
import {
  getUserList,
  deleteById,
  addUser,
  search
} from '@/api/user';

export default{
  data(){
    return{
      searchForm: {
        name: "",
        sex: "",
      },
      searchName: '',
      searchSex: null,
      total: 0,
      userData:[],
      pageData:[],
      pageSize: 10,
      currentPage: 1,
      dialogAddVisible: false,
      addForm: {},
      rules:{
          id: [
            {
              required: true,
              message: '请输入用户编号',
              trigger: 'blur'
            }
          ],
          name: [
            {
              required: true,
              message: '请输入用户名称',
              trigger: 'blur'
            }
          ],
          sex: [
            {
              required: true,
              message: '请选择用户性别',
              trigger: 'blur'
            }
          ],
          age: [
            {
              required: true,
              message: '请输入用户年龄',
              trigger: 'blur'
            }
          ],
          nickname: [
            {
              required: true,
              message: '请输入用户昵称',
              trigger: 'blur'
            }
          ],
          mobile: [
            {
              required: true,
              message: '请输入用户电话',
              trigger: 'blur'
            }
          ],
          stateName: [
            {
              required: true,
              message: '请输入用户状态',
              trigger: 'blur'
            }
          ],
          courseOrder: [
            {
              required: true,
              message: '请输入已购课程',
              trigger: 'blur'
            }
          ],
          courseNum: [
            {
              required: true,
              message: '请输入在学课程',
              trigger: 'blur'
            }
          ],
          address: [
            {
              required: true,
              message: '请输入用户地址',
              trigger: 'blur'
            }
          ]
      },
    }
  },
  mounted(){
    this.getUserData()
  },
  methods: {
    getUserData(){
      getUserList()
      .then((res) => {
        if(res.data.code === 200) {
          this.userData = res.data.data;
          this.total = this.userData.length
          this.getPageInfo()
        } else{
          this.$message.error("数据获取失败")
        }
      }).catch((error) => {
        this.$message.error("服务器连接错误")})
    },
    //获取当前页的用户数据
    getPageInfo() {
      this.pageData = []
      for(let i = (this.currentPage - 1) * this.pageSize; i < this.total; i++){
        this.pageData.push(this.userData[i])
        if(this.pageData.length === this.pageSize){
          break;
        }
      }
    },
    onSubmit(){
      this.$confirm("确认保存该内容", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: 'warning'
      }).then(() =>[
        addUser(this.addForm)
        .then(res => {
          if(res.data.code === 200){
            this.$message.success(res.data.message)
            this.getUserData()
            this.dialogAddVisible = false
          }else{
            this.$message.warning("添加用户失败")
          }
        }).catch(error => {
          this.$message.error("服务器连接失败")
        })
      ]).catch(() => {
        this.$message.info("已取消编辑")
      })
    },
    //通过路由参数传递
    changeView(path, rowData) {
        this.$router.push({
          path: path,
          query: { data: JSON.stringify(rowData) }
        });
      },
    //搜索
      search() {
          console.log("查询条件:", this.searchName, this.searchSex);
          // 检查查询条件是否为空
          if (!this.searchName && this.searchSex == null) {
              this.$message.warning("查询条件不能为空");
              return;
          }
          // 发送查询请求
          search({ name: this.searchName, sex: this.searchSex })
              .then((res) => {
                  if (res.data.code === 200) {
                      console.log("用户列表:", res.data.data);
                      this.userData = res.data.data; // 修复取数据的细节
                      this.total = this.userData.length;
                      this.getPageInfo(); // 保持分页信息更新
                  } else {
                      this.$message.warning("查询失败");
                  }
              })
              .catch((error) => {
                this.$message.error("服务器连接失败");
              });
        },
    //重置
    handleClear() {
      this.searchName = ''
      this.searchSex = ''
    },
    // 切换每页显示条数
    handleSizeChange(size) {
      this.pageSize = size;
      this.getPageInfo()
    },
    // 点击某一页，跳转某一页
    handleCurrentChange(val) {    
      this.currentPage = val;
      this.getPageInfo()
    },
    add(){
      this.addForm = {}
      this.dialogAddVisible =  true
    },
    refresh(){
      this.currentPage = 1,
      this.getUserData()
    },
    // 删除
    deleteUser(id){
      this.$confirm("确认删除该用户?", "提示", {
          confirmButtonText: "确实",
          cancelButtonText: "取消",
          type: "warning"
      }).then(() => {
            deleteById(id)
            .then(res => {
              if(res.data.code === 200){
                this.$message.success(res.data.message);
                this.getUserData()
              }else{
                this.$message.error("删除失败")
              }
            }).catch(error => {
              this.$message.error("服务器连接失败")
            })
      }).catch(() => {
              this.$message.info("已取消删除")
      })
    },
  },
}
</script>

<style>
.content {
  margin: 20px 0px;
}

.el-table {
  margin: 20px 0px;
  text-align: center;
}
</style>